package com.huxiu.yd.utils;

import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.webkit.WebView;
import android.widget.ListView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.huxiu.yd.App;
import com.huxiu.yd.LogInActivity;
import com.huxiu.yd.R;
import com.huxiu.yd.ShareActivity;
import com.huxiu.yd.net.model.Province;

import java.io.Closeable;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

/**
 * Created by yao on 15/7/25:下午5:32.
 */
@SuppressWarnings({"unused", "SetJavaScriptEnabled"})
public class Utils {

    public static void askLogIn(Activity activity) {
        activity.startActivity(new Intent(activity, LogInActivity.class));
    }

    public static void setDefaultWebSettings(WebView webview) {
        webview.getSettings().setDefaultTextEncodingName("UTF-8");
//        webview.getSettings().setUseWideViewPort(true);
        webview.getSettings().setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
        webview.getSettings().setJavaScriptEnabled(true);
        webview.getSettings().setDomStorageEnabled(true);
        webview.getSettings().setBuiltInZoomControls(false);
        webview.setScrollBarStyle(WebView.SCROLLBARS_INSIDE_OVERLAY);
        webview.setWebChromeClient(new WebChromeClient() {
            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                return super.onJsAlert(view, url, message, result);
            }

            @Override
            public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {
                return super.onJsConfirm(view, url, message, result);
            }
        });
    }

    public static String getChannel(Context context) {
        String channel = null;
        try {
            PackageManager pm = context.getPackageManager();
            ApplicationInfo app = pm.getApplicationInfo(context.getPackageName(),
                    PackageManager.GET_META_DATA);
            channel = String.valueOf(app.metaData.get("UMENG_CHANNEL"));
        } catch (Exception ignored) {
        }
        if (TextUtils.isEmpty(channel)) {
            channel = "null";
        }
        return channel;
    }

    public static String getVersionName(Context context) {
        PackageManager pm = context.getPackageManager();
        String versionName = "Unknown";
        try {
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
            versionName = pi.versionName;
        } catch (PackageManager.NameNotFoundException ignored) {
        }
        return versionName;
    }

    public static String getVersionCode(Context context) {
        PackageManager pm = context.getPackageManager();
        String versionCode = "0";
        try {
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
            versionCode = String.valueOf(pi.versionCode);
        } catch (PackageManager.NameNotFoundException ignored) {
        }
        return versionCode;
    }

    public static void showToast(int resId) {
        Toast.makeText(App.getInstance(), resId, Toast.LENGTH_SHORT).show();
    }

    public static void showToast(String msg) {
        Toast.makeText(App.getInstance(), msg, Toast.LENGTH_SHORT).show();
    }

    private static final long SECOND_GAP = 5 * 1000;

    public static String getDateString(long create_time) {
//        Context context = App.getInstance();
//        long now = System.currentTimeMillis();
//        long time = create_time * 1000;
//        if (now - time < SECOND_GAP) {
//            return context.getString(R.string.just_now);
//        } else if (isInSameMinute(time, now)) {
//            return (now - time) / 1000 + "秒前";
//        } else if (isInSameHour(time, now)) {
//            return (now - time) / 60 / 1000 + "分钟前";
//        } else {
//            Calendar nowCal = Calendar.getInstance();
//            nowCal.setTime(new Date(now));
//            Calendar sendCal = Calendar.getInstance();
//            sendCal.setTime(new Date(time));
//            if (nowCal.get(Calendar.YEAR) == sendCal.get(Calendar.YEAR) && nowCal.get(Calendar
//                    .DAY_OF_YEAR) == sendCal.get(Calendar.DAY_OF_YEAR)) {
//                return (now - time) / 60 / 60 / 1000 + "小时前";
//            } else if (nowCal.get(Calendar.YEAR) == sendCal.get(Calendar.YEAR) && nowCal.get
//                    (Calendar.MONTH) == sendCal.get(Calendar.MONTH)) {
//                return ((now - time) / 24 / 60 / 60 / 1000 + 1) + "天前";
//            }
//        }
        Date date = new Date(create_time * 1000);
        return String.valueOf(DateFormat.format("yyyy-MM-dd", date));
    }

    public static Province[] getProvinces() {
        InputStream is = null;
        Reader reader = null;
        try {
            is = App.getInstance().getAssets().open("cities.txt");
            reader = new InputStreamReader(is);
            return new Gson().fromJson(reader, Province[].class);
        } catch (Exception ignored) {

        } finally {
            closeSilently(reader);
            closeSilently(is);
        }
        return new Province[0];
    }

    public static void closeSilently(Closeable closeable) {
        try {
            if (closeable != null) {
                closeable.close();
            }
        } catch (Exception ignored) {

        }
    }

    public static int dip2px(float dpValue) {
        final float scale = App.getInstance().getResources().getDisplayMetrics().density;
        return (int) ((dpValue * scale) + 0.5f);
    }

    public static void doCopy(String text) {
        ClipboardManager cm = (ClipboardManager) App.getInstance()
                .getSystemService(Context.CLIPBOARD_SERVICE);
        cm.setPrimaryClip(ClipData.newPlainText("", text));
    }

    private static final int MINUTE_MILLI = 60 * 1000;

    public static boolean isInSameMinute(long sendTime, long now) {
        return now - sendTime < MINUTE_MILLI;
    }

    private static final int HOUR_MILLI = 60 * 60 * 1000;

    public static boolean isInSameHour(long sendTime, long now) {
        return now - sendTime < HOUR_MILLI;
    }

    private static final ThreadLocal<java.text.DateFormat> yesterdayFormat
            = new ThreadLocal<java.text.DateFormat>() {
        @Override
        protected java.text.DateFormat initialValue() {
            return new SimpleDateFormat("昨天 HH:mm");
        }
    };

    public static final ThreadLocal<java.text.DateFormat> dateFormat
            = new ThreadLocal<java.text.DateFormat>() {
        @Override
        protected java.text.DateFormat initialValue() {
            return new SimpleDateFormat("yyyy-MM-dd");
        }
    };

    private static final ThreadLocal<java.text.DateFormat> shortDateFormat
            = new ThreadLocal<java.text.DateFormat>() {
        @Override
        protected java.text.DateFormat initialValue() {
            return new SimpleDateFormat("yy-MM-dd");
        }
    };

    private static final ThreadLocal<java.text.DateFormat> shortDateFormatNoYear
            = new ThreadLocal<java.text.DateFormat>() {
        @Override
        protected java.text.DateFormat initialValue() {
            return new SimpleDateFormat("MM-dd");
        }
    };

    private static final ThreadLocal<java.text.DateFormat> dayFormat
            = new ThreadLocal<java.text.DateFormat>() {
        @Override
        protected java.text.DateFormat initialValue() {
            return new SimpleDateFormat("yyyy-MM-dd HH:mm");
        }
    };

    private static final ThreadLocal<java.text.DateFormat> dayFormatNoYear
            = new ThreadLocal<java.text.DateFormat>() {
        @Override
        protected java.text.DateFormat initialValue() {
            return new SimpleDateFormat("MM-dd HH:mm");
        }
    };

    private static final ThreadLocal<java.text.DateFormat> datetimeFormat
            = new ThreadLocal<java.text.DateFormat>() {
        @Override
        protected java.text.DateFormat initialValue() {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            sdf.setTimeZone(TimeZone.getTimeZone("GMT+8"));
            return sdf;
        }
    };

    public static String getTimeShowText(Date datetime, Date yesterday, Date today, Date year) {
        if (datetime == null) {
            return null;
        }
        if (yesterday != null && datetime.before(yesterday)) {
            if (datetime.after(year)) {
                return getDayStringNoYear(datetime);
            } else {
                return getDayString(datetime);
            }
        } else if (today != null && datetime.before(today)) {
            return getYesterDayString(datetime);
        }
        return getTodayString(datetime);
    }

    public static String getDayString(Date date) {
        if (date != null) {
            return dayFormat.get().format(date);
        }
        return "";
    }

    public static String getDayStringNoYear(Date date) {
        if (date != null) {
            return dayFormatNoYear.get().format(date);
        }
        return "";
    }

    public static String getYesterDayString(Date date) {
        if (date != null) {
            return yesterdayFormat.get().format(date);
        }
        return "";
    }

    public static String getTodayString(Date date) {
        if (date != null) {
            return todayFormat.get().format(date);
        }
        return "";
    }

    private static final ThreadLocal<java.text.DateFormat> todayFormat
            = new ThreadLocal<java.text.DateFormat>() {
        @Override
        protected java.text.DateFormat initialValue() {
            return new SimpleDateFormat("HH:mm");
        }
    };

    public static void scrollListView(final ListView listView, final int index, final int time) {
        new AsyncTask<Void, Integer, Void>() {
            @Override
            protected Void doInBackground(Void... params) {
                try {
                    Thread.currentThread().sleep(time);
                } catch (InterruptedException e) {
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void result) {
                super.onPostExecute(result);
                if (listView != null && index >= 0) {
                    listView.setSelection(index);
                }
            }

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                if (listView != null && index >= 0) {
                    listView.setSelection(index);
                }
            }
        }.executeOnExecutor(android.os.AsyncTask.THREAD_POOL_EXECUTOR);
    }

    public static void launchShareActivity(Activity activity, String title, String url, String type,
                                           String imageUrl, String description, Bitmap image) {
        Intent intent = new Intent(activity, ShareActivity.class);
        intent.putExtra("title", title);
        intent.putExtra("url", url);
        intent.putExtra("type", type);
        Bitmap bmp = ImageUtils.getWeChatShareBitmap(image);
        if (bmp != null)
            intent.putExtra("image", bmp);
        if (imageUrl != null)
            intent.putExtra("imageUrl", imageUrl);
        if (description != null)
            intent.putExtra("description", description);
        activity.startActivity(intent);
    }

    public static String toHexString(byte[] bytes) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : bytes) {
            String doubleBit = Integer.toHexString(b & 0xff);
            if (doubleBit.length() == 1) {
                hexString.append('0');
            }
            hexString.append(doubleBit);
        }
        return hexString.toString().toLowerCase();
    }

    public static String getEncryptedPassword(String password) {
        try {
            MessageDigest m = MessageDigest.getInstance("MD5");
            byte[] data = password.getBytes();
            return toHexString(m.digest(data));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return password;
        }
    }

    public static void makeCall(Context context, String number) {
        if (TextUtils.isEmpty(number)) {
            return;
        }
        try {
            Intent intent = new Intent(Intent.ACTION_DIAL, Uri.fromParts("tel",
                    number, null));
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        } catch (Exception e) {
            Toast.makeText(context, "该设备不支持拨打电话功能", Toast.LENGTH_LONG).show();
        }
    }

    public static void closeKeyboard(View view) {
        InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

    public static void showErrorMsg(VolleyError error) {
        Throwable t = error.getCause();
        if (t instanceof ErrorResponseException) {
            String msg = error.getMessage();
            if (!"内容为空".equals(msg) && !"数据为空".equals(msg)
                    && !msg.contains("哦")
                    ) {
                Utils.showToast(msg);
            }
        } else {
            Utils.showToast(R.string.generic_failure);
        }
    }

}
